# -*- encoding: utf-8 -*-

"""
@File:      tc_libtalloc_libtalloc_func_001.py
@Time:      2024/04/02 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libtalloc_libtalloc_func_001.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libtalloc libtalloc-devel gcc valgrind"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >talloc_test1.c<<"EOF"
#include <stdio.h>
#include <talloc.h>

int main() {
    void *root = talloc_new(NULL); // 创建新的 talloc 上下文
    if (root == NULL) {
        fprintf(stderr, "Failed to create a new talloc context\\n");
        return -1;
    }

    // 分配多个字符串
    for (int i = 0; i < 10; i++) {
        char *str = talloc_asprintf(root, "String %d", i);
        if (str == NULL) {
            fprintf(stderr, "Failed to allocate memory for string\\n");
            talloc_free(root);
            return -1;
        }
    }

    // 测试是否有任何内存泄漏发生
    talloc_report_full(root, stderr);

    // 正常释放所有分配的内存
    talloc_free(root);

    // 再次测试内存泄漏（root 上下文应该已被释放）
    talloc_report_full(NULL, stderr);

    return 0;
}
EOF'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o talloc_test1 talloc_test1.c -ltalloc")
        self.cmd("valgrind --leak-check=full ./talloc_test1 > talloc.log 2>&1")
        code, talloc_result = self.cmd("cat talloc.log", ignore_status=True)
        self.assertIn("All heap blocks were freed -- no leaks are possible", talloc_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf talloc_test1.c talloc_test1 talloc.log")
